var util = require('../../utils/util.js');
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */   
  data: {
    swiperCon: {
      imgUrls: [],
      indicatorDots: true, //是否显示面板指示点
      indicatorColor: "#fa7d35", //指示点颜色
      indicatorActiveColor: "#ffffff", //当前选中的指示点颜色
      autoplay: true, //是否自动切换
      interval: 5000, //自动切换时间间隔
      duration: 1000, //滑动动画时长
      circular: true, //是否采用衔接滑动
    },
    city_name: "",
    adv_list: [],
    tradeList: [],
    indexList: [],
    hot_list: [],
    special_id: "",
    detail: [], //商品列表
    goods_title: "",

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    util.postUrl('search/hot_words', {}, function(res) {
      that.setData({
        hot_list: res.data.datas,
      })
    })
    wx.getLocation({
      success: function(res) {
        console.log(res);
        util.postUrl("index/get_special", {
          lay_x: res.latitude,
          lay_y: res.longitude,
        }, function(res) {
          that.setData({
            city_name: res.data.datas.city_name,
            special_id: res.data.datas.special_id,
          
          })
          app.user_city_id = res.data.datas.user_city_id;
          that.getIndex(res.data.datas.special_id);
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  getIndex: function(id) {
    var that = this;
    util.postUrl('index/index', {
      special_id: id,
    }, function(res) {
      if (res.data.code == 200) {
        var indexList = res.data.datas.list;
        for (let item of indexList) {
          if (item.name == "goods") {
            var temp = item.item;
            that.setData({
              goods_title: item.title,
            })
            for (var i = 0; i < temp.length; i++) {
              if (temp[i].min_goods_price == temp[i].max_goods_price) {
                temp[i].price = temp[i].min_goods_price
              } else {
                temp[i].price = temp[i].min_goods_price + " - ￥" + temp[i].max_goods_price
              }
              for (var j = 0; j < temp[i].spec_list.length; j++) {
                var temp_goods = wx.getStorageSync('temp_goods');
                temp[i].spec_list[j].num = 0;
                if (wx.getStorageSync('token') == '') {
                  for (var z = 0; z < temp_goods.length; z++) {
                    if (temp_goods[z].goods_id == temp[i].spec_list[j].goods_id) {
                      temp[i].spec_list[j].num = temp_goods[z].quantity;
                    }
                  }
                } else {
                  var member_carts = res.data.datas.member_carts;
                  var num = member_carts[temp[i].spec_list[j].goods_id];
                  if (num) {
                    temp[i].spec_list[j].num = num;
                  }
                }
              }
            }
            that.initRed();
            that.setData({
              detail: temp,
            })
          }
        }
        that.setData({
          indexList: indexList,

        })
      }

    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (app.choose_city != '') {
      that.setData({
        city_name: app.choose_city.city_name,
        special_id: app.choose_city.special_id,
      })
    }
    that.getIndex(that.data.special_id);


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  goSearch: function(e) {
    var name = e.currentTarget.dataset.name;
    if (name) {
      wx.navigateTo({
        url: '../search/search?name=' + name,
      })
    } else {
      wx.navigateTo({
        url: '../search/search',
      })
    }

  },
  goLocation: function() {
    var that = this;
    wx.navigateTo({
      url: '../indexLocation/indexLocation?city_name=' + that.data.city_name,
    })
  },
  goGoodsDetail: function(e) {
    var item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../goods-details/goods-details?item=' + JSON.stringify(item),
    })

  },
  goClass: function(e) {
    var item = e.currentTarget.dataset.class;
    app.class_id = item;
    console.log(item);
    wx.switchTab({
      url: '../classify/classify'
    })
  },
  //更新购物车气泡数
  initRed: function() {
    var that = this;
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      var sum = 0;
      if (temp_goods != '') {
        for (var i = 0; i < temp_goods.length; i++) {
          sum = sum + temp_goods[i].quantity;
        }
      }

      if (sum == 0) {
        wx.hideTabBarRedDot({
          index: 2,
        })
      } else {
        wx.setTabBarBadge({
          index: 2,
          text: sum + "",
        })
      }

    } else {
      util.postUrl('cart/cart_count', {}, function(res) {
        if (res) {
          if (res.data.datas.count.goods_total_num == 0) {
            wx.hideTabBarRedDot({
              index: 2,
            })
          } else {
            wx.setTabBarBadge({
              index: 2,
              text: (res.data.datas.count.goods_total_num + ""),
            })
          }
        }
      })
    }

  },
  //点击减号
  bindMinus: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];

    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (item.num - 1 < 0) {
      return;
    }
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          if (item.num - 1 == 0) {
            temp_goods.splice(i, 1);
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
          } else {
            temp_goods[i].quantity = item.num - 1;
            temp_goods[i].goods_num = item.num - 1;
          }
        }
      }
      item.num = item.num - 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);
      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      if (item.num - 1 == 0) {
        util.postUrl("cart/cart_remove", {
          cart_id: item.goods_id,
          del_type: 2,
        }, function(res) {
          if (res) {
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
            wx.setStorageSync("check_list", check_list);
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          }
        })
      } else {
        util.postUrl('cart/cart_add', {
          goods_id: item.goods_id,
          quantity: item.num - 1,
        }, function(res) {
          if (res) {
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          } else {}
        })
      }
    }
  },

  /* 点击加号 */
  bindPlus: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];
    item.num = parseInt(item.num);
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num + 1;
          temp_goods[i].goods_num = item.num + 1;
          flag = false;
        }
      }
      if (flag) {
        check_list.push(item.goods_id);
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num + 1,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num + 1,
          goods_price: item.goods_price,
        });
      }
      item.num = item.num + 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);

      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: item.num + 1,
      }, function(res) {
        if (res) {
          if (res.data.code == 400) {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'success',
              duration: 2000
            })
            return;
          }
          if (check_list.indexOf(item.goods_id) == -1) {
            check_list.push(item.goods_id);
          }
          wx.setStorageSync('check_list', check_list);
          console.log(check_list);
          item.num = item.num + 1;
          that.setData({
            detail: temp
          });
          that.initRed();
        } else {}
      })
    }

  },
  /* 输入框事件 */
  bindManual: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;

    var item = temp[index].spec_list[spec_index];
    // var index = e.currentTarget.dataset.index;
    console.log(item);
    var temp_num = parseInt(item.num);
    // 将数值与状态写回
    console.log(e.detail.value)
    if (e.detail.value == '' || e.detail.value == 0) {
      e.detail.value = 1;
    }
    item.num = parseInt(e.detail.value);
    that.setData({
      detail: temp,
    })
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num;
          temp_goods[i].goods_num = item.num;
          flag = false;
        }
      }
      if (flag) {
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num,
          goods_price: item.goods_price,
        });
      }
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      console.log('temp_goods', wx.getStorageSync('temp_goods'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: parseInt(e.detail.value),
      }, function(res) {
        if (res.data.code == 200) {
          that.initRed();

        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
          item.num = temp_num;
          that.setData({
            detail: temp
          });
          that.initRed();
        }
      })
    }

  },
  //点击显示隐藏
  onChangeShowState: function(e) {
    var that = this;
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var temp = that.data.detail;
    if (temp[index].showView) {
      temp[index].showView = false;
    } else {
      temp[index].showView = true;
    }
    that.setData({
      detail: temp,
    })
  },
  GoSome: function(e) {
    console.log(e.currentTarget.dataset);
    var mytype = e.currentTarget.dataset.type;
    var data = e.currentTarget.dataset.data;

    //跳搜索
    if (mytype == "keyword") {
      if (data == "") {
        return;
      }
      wx.navigateTo({
        url: '../search/search?name=' + data,
      })
      return;

    }
    //跳分类
    if (mytype == "category") {
      if (data == "") {
        return;
      }
      app.class_id = data;
      wx.switchTab({
        url: '../classify/classify'
      })
      return;

    }
    //跳专题
    if (mytype == "special") {
      if (data == "") {
        return;
      }
      wx.navigateTo({
        url: '../special_index/special_index?special_id=' + data,
      })
      return;
    }
    //跳商品
    if (mytype == "goods") {
      if (data == "") {
        return;
      }
      var item = {
        goods_id: data,
      };
      wx.navigateTo({
        url: '../goods-details/goods-details?item=' + JSON.stringify(item),
      })
      return;

    }
    //跳店铺
    if (mytype == "store") {
      if (data == "") {
        return;
      }
      wx.navigateTo({
        url: '../shop_detail/shop_detail?store_id=' + data
      })
      return;

    }
    //优惠券
    if (mytype == "coupon") {
      if (data == "") {
        return;
      }
      if (wx.getStorageSync('token') == '') {
        wx.switchTab({
          url: '../me/me',
        })
        return;
      }
      util.postUrl('member_red_packet/add_red_packet', {
        packet_id: data
      }, function(res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '领取优惠券成功！',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
        }

      })
      return;

    }
  }
})